package com.yuanlp.mobileplayer.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yuanlp.mobileplayer.R;
import com.yuanlp.mobileplayer.bean.MediaItem;
import com.yuanlp.mobileplayer.utils.Utils;
import com.yuanlp.mobileplayer.view.MyVideoView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

/**
 * Created by 原立鹏 on 2017/7/16.
 * 系统播放器
 * 注意去Manifext.xml里注册
 */

public class SystemVideoPlayer extends Activity implements View.OnClickListener {
    private static final int PROGRESS = 1;  //处理视频播放进度
    private static final int HIDEVIDEO = 2;  //设置handler的what，隐藏视频播放页面的布局
    private MyVideoView videoview;
    private Uri uri;
    private Utils utils;
    private MyReceiver receiver;  //电量监听的广播接收者
    private static final String TAG = "SystemVideoPlayer";

    private LinearLayout llTop;
    private TextView tvName;
    private ImageView ivBattery;
    private TextView tvSystemTime;
    private Button btnVoice;
    private SeekBar seekbarVoice;
    private Button switchPlayer;
    private LinearLayout llBottom;
    private TextView tvCurrentTime;
    private SeekBar seekbarVideo;
    private TextView tvDuration;
    private Button btExit;
    private Button btVideoPre;
    private Button btVideoStartPause;
    private Button btNext;
    private Button btVideoSwitchScreen;
    private int duration;
    private ArrayList<MediaItem> medialist;  //传入的视频列表
    private int position;  //播放视频的列表中的位置

    private GestureDetector dector;  // 手势识别器
    private RelativeLayout media_controller; //视频页面的控制按键布局

    private boolean isShow=false;  //判定控制布局是否显示,默认是隐藏的
    private boolean isFullScreen;   //判断是否是全屏
    public int FULLSCREEN=1;    //  全屏
    public int DEFAULTSCREEN=2; //默认屏幕

    private int screenWidth;
    private int screenHeight; //屏幕高
    private int videoHeight; //视频的高度
    private int videoWidth;  //视频的宽度

    private AudioManager audioManager;  //音量管理器
    private int currentVoice;  //当前音浪
    private int maxVoice; //最大音量
    private boolean isMuteVoice; //是否静音

    private float startY;  //在屏幕上滑动调节音量时，开始的Y轴值
    private float touchRange;  //屏幕的高，因为涉及到横竖屏切换，到时候会取小的值
    private int touchVoice; //滑动时的音量
    private boolean isNetUri;  //根据地址判断是否是网络资源

    private LinearLayout buffering;  //显示视频卡顿时的布局，其中有一个progressbar和网速显示
    private TextView tv_netspeed;  //显示网速的控件

    private LinearLayout ll_loading;  //加载视频时的初始化布局
    private TextView tv_loading_netspeed;  //加载视频时的初始化网速
    private static final int SPEED=3;  //当前网速判断的一个case

    private boolean isSystemSpeed=false;  //是否调用系统自定义的测速

    private void findViews() {
        setContentView(R.layout.system_video_player);

        llTop = (LinearLayout)findViewById( R.id.ll_top );
        tvName = (TextView)findViewById( R.id.tv_name );
        ivBattery = (ImageView)findViewById( R.id.iv_battery );
        tvSystemTime = (TextView)findViewById( R.id.tv_system_time );
        btnVoice = (Button)findViewById( R.id.btn_voice );
        seekbarVoice = (SeekBar)findViewById( R.id.seekbar_voice );
        switchPlayer = (Button)findViewById( R.id.switch_player );
        llBottom = (LinearLayout)findViewById( R.id.ll_bottom );
        tvCurrentTime = (TextView)findViewById( R.id.tv_current_time );
        seekbarVideo = (SeekBar)findViewById( R.id.seekbar_video );
        tvDuration = (TextView)findViewById( R.id.tv_duration );
        btExit = (Button)findViewById( R.id.bt_exit );
        btVideoPre = (Button)findViewById( R.id.bt_video_pre );
        btVideoStartPause = (Button)findViewById( R.id.bt_video_start_pause );
        btNext = (Button)findViewById( R.id.bt_next );
        btVideoSwitchScreen = (Button)findViewById( R.id.bt_video_switch_screen );

        videoview= (MyVideoView) findViewById(R.id.videoview);

        btnVoice.setOnClickListener( this );
        switchPlayer.setOnClickListener( this );
        btExit.setOnClickListener( this );
        btVideoPre.setOnClickListener( this );
        btVideoStartPause.setOnClickListener( this );
        btNext.setOnClickListener( this );
        btVideoSwitchScreen.setOnClickListener( this );

        //卡顿时的布局与网速
        buffering= (LinearLayout) findViewById(R.id.buffering);
        tv_netspeed= (TextView) findViewById(R.id.tv_netspeed);

        //加载布局时的布局与网速显示
        ll_loading= (LinearLayout) findViewById(R.id.ll_loading);
        tv_loading_netspeed= (TextView) findViewById(R.id.tv_loading_netspeed);

        /**
         * 这个就是视频页面的顶部与底部的控制器的布局，后面做隐藏时用
         */
        media_controller = (RelativeLayout) findViewById(R.id.media_controller);

        handler.sendEmptyMessage(SPEED);  //控件只要一声明好就发消息去获取网速


    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2017-07-18 09:38:56 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == btnVoice ) {
            // Handle clicks for btnVoice
            isMuteVoice=!isMuteVoice;
           setVoice(currentVoice,isMuteVoice);
//            if (isMuteVoice){
//                //是静音，设置为不静音
//                isMuteVoice=false;
//                seekbarVoice.setProgress(currentVoice);
//                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,currentVoice,0);
//            }else {
//                //不是静音，设置为静音
//                isMuteVoice=true;
//                seekbarVoice.setProgress(0);
//                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,0,0);
//
//            }
        } else if ( v == switchPlayer ) {
            // Handle clicks for switchPlayer

        } else if ( v == btExit ) {
            // Handle clicks for btExit   退出
            finish();
        } else if ( v == btVideoPre ) {
            // Handle clicks for btVideoPre  播放上一个视频
            ll_loading.setVisibility(View.VISIBLE);
            if (medialist!=null&&medialist.size()>0){
                position-=1;
                if (position<=0){
                    position=medialist.size()-1;
                }
                MediaItem mediaitem=medialist.get(position);
                tvName.setText(mediaitem.getName());
                isNetUri=utils.isNetUri(mediaitem.getData());
                videoview.setVideoPath(mediaitem.getData());

            }else if (uri!=null){
                isNetUri=utils.isNetUri(uri.toString());
                tvName.setText(uri.toString());
                videoview.setVideoURI(uri);
            }


        } else if ( v == btVideoStartPause ) {
            // Handle clicks for btVideoStartPause  播放暂停与启动
            startAndPause();
        } else if ( v == btNext ) {
            // Handle clicks for btNext   播放下一个
            //让视频的loading布局显示，当准备好播放时再消失
            ll_loading.setVisibility(View.VISIBLE);
         if (medialist!=null&&medialist.size()>0){
             position+=1;
             if (position>=medialist.size()){
                 position=0;
             }

                 MediaItem mediaItem = medialist.get(position);
                 tvName.setText(mediaItem.getName());
                 isNetUri=utils.isNetUri(mediaItem.getData());
                 videoview.setVideoPath(mediaItem.getData());



         }else if (uri!=null){
             //把上一个下一个按钮设置灰色
             tvName.setText(uri.toString());
             isNetUri=utils.isNetUri(uri.toString());
             videoview.setVideoURI(uri);
             btNext.setEnabled(false);
             btNext.setBackgroundResource(R.drawable.btn_next_gray);
         }

        } else if ( v == btVideoSwitchScreen ) {
            // Handle clicks for btVideoSwitchScreen
            if (isFullScreen){
                setVideoType(DEFAULTSCREEN);
            }else{
                setVideoType(FULLSCREEN);
            }
        }

        handler.removeMessages(HIDEVIDEO);
        handler.sendEmptyMessageDelayed(HIDEVIDEO,3000);
    }

    private void startAndPause() {
        if (videoview.isPlaying()){
            //视频在播放，则暂停
            videoview.pause();
            //按钮图片设置为暂停
            btVideoStartPause.setBackgroundResource(R.drawable.bt_video_play_selector);
        }else{
            //视频在暂停，设置为播放
            videoview.start();
            //按钮图片设置为播放
            btVideoStartPause.setBackgroundResource(R.drawable.bt_video_pause_selector);            }
    }


    private int preCurrentPosition;  //上一次的播放进度
    /**
     * 定义一个handler来处理信息
     */
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SPEED:  //显示当前网速
                    //得到网速
                    String netSpeed = utils.getNetSpeed(SystemVideoPlayer.this);
                    System.out.println("当前网速"+netSpeed);
                    //显示网速
                    tv_loading_netspeed.setText("玩命加载中"+netSpeed);  //loading时的速度显示
                    tv_netspeed.setText("缓冲中"+netSpeed);  //缓冲时的速度显示
                    removeMessages(SPEED);
                    handler.sendEmptyMessageDelayed(SPEED,2000);  //一定要隔2秒才能去获取网速
                    break;
                case PROGRESS:
                    //根据准备好播放时候后，发送的更新视频进度消息，来更新视频进度
                    int currentPosition=videoview.getCurrentPosition();
                    seekbarVideo.setProgress(currentPosition);

                    //设置当前播放的时间，使其显示在播放器上
                    tvCurrentTime.setText(utils.stringForTime(currentPosition));

                    //设置系统播放时间，隔一秒刷新一下
                    tvSystemTime.setText(getSystemTime());

                    //网络资源缓冲
                    if (isNetUri){
                        //只有网络资源有缓冲
                        int bufferPercentage = videoview.getBufferPercentage();  //0~100
                        int totalbuffer = bufferPercentage * seekbarVideo.getMax();
                        int secordProgress=totalbuffer/100;
                        seekbarVideo.setSecondaryProgress(secordProgress);
                    }else{
                        //本地进度条没有缓冲，即第二条进度条为灰色
                        seekbarVideo.setSecondaryProgress(0);
                    }

                    if (!isSystemSpeed){
                        if (videoview.isPlaying()){
                            int buffer=currentPosition-preCurrentPosition;
                            if (buffer<500){
                                //视频卡了
                                buffering.setVisibility(View.VISIBLE);
                            }else{
                                buffering.setVisibility(View.GONE);
                            }

                        }else{
                            buffering.setVisibility(View.GONE);
                        }
                    }
                    preCurrentPosition=currentPosition;
                    //隔一秒刷新一下进度
                    removeMessages(PROGRESS);

                    handler.sendEmptyMessageDelayed(PROGRESS,1000);
                    break;
                case HIDEVIDEO:
                    media_controller.setVisibility(View.GONE);
                    break;
            }
        }
    };


    /**
     * 获取系统时间
     * @return
     */
    private String getSystemTime() {
        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        return format.format(new Date());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: 123");

        utils=new Utils();

        //注册电量广播，像锁屏、开屏、电量变化这样的广播，静态注册的广播接收者收不到广播，因为导致安全问题，所以必须动态注册
        receiver=new MyReceiver();

        IntentFilter intentFilter=new IntentFilter();
        //当电量变化时发这个广播
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(receiver, intentFilter);

        findViews(); //初始化控件

        getData();  //得到播放的视频资源

        /**
         * 获取手机屏幕的宽度高度像素
         */
        DisplayMetrics displayMetrics=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        screenWidth=displayMetrics.widthPixels;
        screenHeight=displayMetrics.heightPixels;

        /**
         * 实例化音量管理器
         */
        audioManager= (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        currentVoice=audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); //当前音量
        maxVoice=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);  //最大音量
        //准备好的监听，监听是否视频准备好
        videoview.setOnPreparedListener(new MyOnPreparedListener());
        //播放出错了的监听
        videoview.setOnErrorListener(new MyOnErrorListener());
        //播放完成的监听
        videoview.setOnCompletionListener(new MyOnCompletionListener());

        //设置控制面板,系统自带的
        //videoview.setMediaController(new MediaController(this));

        //视频进度条监听
        seekbarVideo.setOnSeekBarChangeListener(new VideoOnSeekBarChangeListener());

        //监听网络播放卡顿现象
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            videoview.setOnInfoListener(new MyOnInfoListener());
        }

        //设置音量监听
        seekbarVoice.setOnSeekBarChangeListener(new VoiceOnSeekBarChangeListener());
        //设置音量
        seekbarVoice.setMax(maxVoice);
        seekbarVoice.setProgress(currentVoice);

        System.out.println("onCreate ----------当前声音"+currentVoice);
        //实例化手势识别器，重写长按、双击、单击回调方法
        dector=new GestureDetector(this,new GestureDetector.SimpleOnGestureListener(){

            /**
             * 长按触发的回调函数
             * @param e
             */
            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
                startAndPause();
                Toast.makeText(SystemVideoPlayer.this,"长按里屏幕",Toast.LENGTH_SHORT).show();
            }

            /**
             * 双击触发的函数
             * @param e
             * @return
             */
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                //Toast.makeText(SystemVideoPlayer.this,"双击了屏幕",Toast.LENGTH_SHORT).show();
                isMediaControllerShow();


                if (isFullScreen){
                   //是全屏，则设置为默认
                    setVideoType(DEFAULTSCREEN);
                }else{
                    //是默认，设置全屏
                    setVideoType(FULLSCREEN);
                }
                return super.onDoubleTap(e);

            }

            /**
             * 单击触发的函数
             * @param e
             * @return
             */
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                //Toast.makeText(SystemVideoPlayer.this,"单击了屏幕",Toast.LENGTH_SHORT).show();
                handler.removeMessages(HIDEVIDEO);
                isMediaControllerShow();
                if (isShow){
                    handler.sendEmptyMessageDelayed(HIDEVIDEO,3000);
                }
                return super.onSingleTapConfirmed(e);
            }
        });

    }

    /**
     * 视频播放卡顿时的监听，Android4.2.2后封装到了videoview里了已经
     */
    public class MyOnInfoListener implements MediaPlayer.OnInfoListener

    {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            switch (what){
                case MediaPlayer.MEDIA_INFO_BUFFERING_START: //开始卡顿
                    //显示卡顿的布局
                    buffering.setVisibility(View.VISIBLE);
                    break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_END:  //结束卡顿
                    buffering.setVisibility(View.GONE);
                    break;
            }
            return true;
        }
    }
    private void setVideoType(int screen) {
      if (screen==FULLSCREEN){
          //1、设置视频画面大小
            videoview.setVideoSize(screenWidth,screenHeight);
          //2、设置按钮变化
          btVideoSwitchScreen.setBackgroundResource(R.drawable.bt_video_switch_screen_default_selector);
          //3、设置isFullScreen=true;
          isFullScreen=true;
      }else if (screen==DEFAULTSCREEN){
            int mVideoWidth=videoWidth;  //视频真实宽度
            int mVideoHeight=videoHeight; //视频真实高度

          videoview.setVideoSize(mVideoWidth,mVideoHeight);
          btVideoSwitchScreen.setBackgroundResource(R.drawable.bt_video_switch_screen_full_selector);
          isFullScreen=false;
      }
    }

    //控制视频播放页面控制按钮布局是否显示
    public void isMediaControllerShow() {
        if (isShow){
            media_controller.setVisibility(View.GONE);  //设置隐藏
            isShow=false;

        }else{
            media_controller.setVisibility(View.VISIBLE);
            isShow=true;

        }


    }

    //利用onTouchEvent，传递event事件给手势识别器，否则无法触发手势识别器的回调方法
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        dector.onTouchEvent(event);

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                startY=event.getY();
                currentVoice=audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);  //获取滑动开始时的音量
                touchRange=Math.min(screenHeight,screenWidth);
                handler.removeMessages(HIDEVIDEO);
                break;
            case MotionEvent.ACTION_MOVE:
                float endY=event.getY();     //滑动的距离
                float distance=startY-endY;  //相对滑动的距离
                //float changeVoice=(distance/touchRange)*maxVoice;  //改变的音量
                Log.i(TAG, "onTouchEvent: move里改变的距离"+distance);
                //int voice= (int) Math.min(Math.max(touchVoice+changeVoice,0),maxVoice);  //改变后的音量
//                if (changeVoice!=0){  //当改变的音量不为0时，才去改变音量
//                    setVoice(voice,false);
//                }
                break;
            case MotionEvent.ACTION_UP:
                float upY=event.getY();
                float upDistance=startY-upY;
                float changeVoice=(upDistance/touchRange)*maxVoice;  //改变的音量
                Log.i(TAG, "onTouchEvent: 取消滑动时的距离"+upDistance);
                int voice= (int) Math.min(Math.max(touchVoice+changeVoice,0),maxVoice);  //改变后的音量
                if (changeVoice!=0){  //当改变的音量不为0时，才去改变音量
                    setVoice(voice,false);
                }
                handler.sendEmptyMessageDelayed(HIDEVIDEO,3000);
                break;

        }

        return super.onTouchEvent(event);
    }

    /**
     * 当按手机的增加音量、减少音量时，相应的改变音量与进度条
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_VOLUME_DOWN){
            currentVoice--;
            setVoice(currentVoice,false);
            handler.removeMessages(HIDEVIDEO);
            handler.sendEmptyMessageDelayed(HIDEVIDEO,3000);
            return true;
        }else if (keyCode==KeyEvent.KEYCODE_VOLUME_UP){
            currentVoice++;
            setVoice(currentVoice,false);
            handler.removeMessages(HIDEVIDEO);
            handler.sendEmptyMessageDelayed(HIDEVIDEO,3000);
            return  true;  //如果返回false，那么seekbar变化，同时系统的音量条也会出现，不好看。
        }

        return super.onKeyDown(keyCode, event);
    }

    public void getData(){
        //得到播放地址,从intent中获取
        uri = getIntent().getData();

        //获取videopager里传过来的list数据，包含media列表的信息
        medialist = (ArrayList<MediaItem>) getIntent().getSerializableExtra("mediallist");
        position = getIntent().getIntExtra("position",0);

        if (medialist!=null && medialist.size()>0){
            //当list不为空，那么优先播放列表中的数据
            MediaItem mediaItem = medialist.get(position);
            tvName.setText(mediaItem.getName());
            isNetUri=utils.isNetUri(mediaItem.getData());
            videoview.setVideoPath(mediaItem.getData());

        }else if (uri!=null){
            tvName.setText(uri.toString());
            isNetUri=utils.isNetUri(uri.toString());
            //uri=Uri.parse("http://localhost:8080/Honor.mp4");
            videoview.setVideoURI(uri);
        }else{
            Toast.makeText(SystemVideoPlayer.this,"你没有传递数据",Toast.LENGTH_SHORT).show();
        }

    }
    /**
     * 监听电量变化的广播接收者
     */
    class MyReceiver extends BroadcastReceiver{


        @Override
        public void onReceive(Context context, Intent intent) {
            int level=intent.getIntExtra("level",0);  //去intent获取key为level的值，默认是0
            setBattery(level);
        }
    }

    /**
     * 电量变化的方法
     * @param level
     */
    private void setBattery(int level) {
        if (level<=0){
            ivBattery.setImageResource(R.drawable.ic_battery_0);
        }else if (level<=10){
            ivBattery.setImageResource(R.drawable.ic_battery_10);
        }else if (level<=20){
            ivBattery.setImageResource(R.drawable.ic_battery_20);
        }else if (level<=40){
            ivBattery.setImageResource(R.drawable.ic_battery_40);
        }else if (level<60){
            ivBattery.setImageResource(R.drawable.ic_battery_60);
        }else if (level<=80){
            ivBattery.setImageResource(R.drawable.ic_battery_80);
        }else if (level<=100){
            ivBattery.setImageResource(R.drawable.ic_battery_100);
        }
    }

    /**
     * 视频播放框中的进度条拖拽变化的监听
     */
    class VideoOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {


        /**
         * 手指在seekbar上滑动时触发
         * @param seekBar
         * @param progress
         * @param fromUser   是否是人为的滑动导致的seekbar变化，系统自动滑动也会导致这个回调方法
         */
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser){
                videoview.seekTo(progress);   //可以查看mediaplayer的声明周期图，里面有这个方法。
            }
        }

        /**
         * 点击seekbar时触发
         * @param seekBar
         */
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            //当手在点击seekbar时，阻止handler发消息去隐藏控制栏
            handler.removeMessages(HIDEVIDEO);
        }


        /**
         * 离开seekbar时触发
         * @param seekBar
         */
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            //当手离开seekbar时，触发handler发消息去隐藏控制栏
            handler.sendEmptyMessageDelayed(HIDEVIDEO,3000);

        }
    }

    /**
     * 音量进度条变化监听
     */
    class VoiceOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser){
                if (progress>0){
                    isMuteVoice=false;
                }else{
                    isMuteVoice=true;
                }
                setVoice(progress,isMuteVoice);
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            handler.removeMessages(HIDEVIDEO);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            handler.sendEmptyMessageDelayed(HIDEVIDEO,3000);
        }
    }

    public void setVoice(int progress,boolean isMuteVoice) {
        if (isMuteVoice){
            seekbarVoice.setProgress(0);
            //音量控制器控制音量变化
            //audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,1);  //第三个参数设置1，表示显示系统音量进度
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,0,0);  //第三个参数设置1，表示显示系统音量进度

        }else {

            //音量控制器控制音量变化
            //audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,1);  //第三个参数设置1，表示显示系统音量进度
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,0);
            seekbarVoice.setProgress(progress);
            currentVoice=progress;  //把音量赋值给当前音量
            Log.d(TAG, "setVoice: 当前声音"+currentVoice);
            System.out.println("setVoice ----------当前声音"+currentVoice);
        }

    }

    /**
     * 准备好播放时的监听
     */
    class MyOnPreparedListener implements MediaPlayer.OnPreparedListener {

        @Override
        public void onPrepared(MediaPlayer mp) {
            videoview.start(); //开始播放
            duration = videoview.getDuration();  //获取视频总时长
            seekbarVideo.setMax(duration);   //设置播放进度的最大值

            //发送消息，来更新视频进度
            handler.sendEmptyMessage(PROGRESS);

            //设置显示的视频总时长
            tvDuration.setText(utils.stringForTime(duration));

            //默认进入播放时，隐藏
            media_controller.setVisibility(View.GONE);
            isShow=false;  //设置为隐藏

            //获取播放器播放视频的宽度和高度
            videoHeight=mp.getVideoHeight();
            videoWidth=mp.getVideoWidth();
           // videoview.setVideoSize(mp.getVideoWidth(),mp.getVideoHeight());

            setVideoType(DEFAULTSCREEN);

            //当准备好播放时，把loading页面消失掉
            ll_loading.setVisibility(View.GONE);

        }
    }

    /**
     * 播放出错
     */
    class MyOnErrorListener implements MediaPlayer.OnErrorListener {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            //出错后，系统会自动提示播放出错，同时自己也弹一个吐司
            Toast.makeText(SystemVideoPlayer.this,"播放出错",Toast.LENGTH_SHORT).show();
            //播放出错的原因
            //1.播放的视频格式不支持  ----解决办法，跳转到万能播放器去播放
            //2.播放网络视频时，网路中断   -----如果网络确实断了，提示用户网络断了；如果网络断断续续，重新播
            //3.播放的视频中间有空白  -----只能去重新下载
            return true;
        }
    }

    /**
     * 播放完成的监听
     */
    class MyOnCompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            //播放完成后，自动播放下一个
            if (medialist!=null && medialist.size()>0){
                position+=1;
                if (position>=medialist.size()){
                    position=0;
                }
                MediaItem mediaItem = medialist.get(position);
                tvName.setText(mediaItem.getName());
                videoview.setVideoPath(mediaItem.getData());
            }else if (uri!=null){
                tvName.setText(uri.toString());
                videoview.setVideoURI(uri);
            }
            Toast.makeText(SystemVideoPlayer.this, "播放完成", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: ");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: 获取焦点");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: ");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart: ");
    }

    @Override
    protected void onDestroy() {
        //释放资源的时候，先释放子类资源，再释放父类资源，因此这里先解除注册的广播，再释放activity
        Log.d(TAG, "onDestroy: ");

        //取消注册
        if (receiver!=null)
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
